package thread

import (
	"strings"
	"time"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/logger"

	"ssforward/common/constant"
	mq "ssforward/common/middleware/mqtt"
	"ssforward/common/utils"
	"ssforward/internal/data/clients"
)

type ClientStatusThread struct {
}

func (ClientStatusThread) Run(threadName string) {
	logger.Infof("启动线程 - %s.", threadName)
	go func() {
		for {
			select {
			case <-time.After(10 * time.Second):
				statusInfo()
			}
		}
	}()
}

func statusInfo() {
	// mq客户端连接状态
	clients.ForwardMqClients.Range(func(k, v interface{}) bool {
		clientId := k.(string)
		serverId := strings.Split(clientId, "-")[1]
		if v != nil {
			client := v.(*mq.Client)
			_ = env.Cache.HashSet(constant.ForwardClientPrefix+serverId, constant.ForwardClientStatus, utils.If(client.IsConnected(), "true", "false").(string))
		} else {
			_ = env.Cache.HashSet(constant.ForwardClientPrefix+serverId, constant.ForwardClientStatus, "false")
		}
		return true
	})
	// db数据库连接状态
	clients.ForwardDbClients.Range(func(clientId, db any) bool {
		serverId := strings.Split(clientId.(string), "-")[1]
		_ = env.Cache.HashSet(constant.ForwardClientPrefix+serverId, constant.ForwardClientStatus, utils.If(db != nil, "true", "false").(string))
		return true
	})

}
